<template>
    <div class="box">
        <h4>发表评论</h4>
        <textarea placeholder="请输入要BB的内容（最多吐槽120个字）" maxlength="120" v-model="msg"></textarea>
        <mt-button type="primary" size="large" @click="publishComment">发表评论</mt-button>

        <!-- 评论列表区域 -->
        <div class="cmt-list">
            <div class="cmt-item" v-for="(item,index) in commentData" :key="index">
                <div class="cmt-item-title">第 {{ index+1 }} 楼&nbsp;用户：{{ item.username }}&nbsp;发表时间：{{ item.add_time | formatDate }}</div>
                <div class="cmt-item-body">{{ item.content }}</div>
            </div>
        </div>

        <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
    </div>
</template>

<script>
import { Toast } from 'mint-ui'
export default {
    data(){
        return {
            pageindex:1,
            commentData:[],
            msg:''
        }
    },
    created(){
        this.getComment();
    },
    methods:{
        async getComment(){
            let res = await this.$http.get('/api/getcomments?id='+this.newsid+'&pageindex='+this.pageindex);
            // console.log(res.data);
            //数据拼接 点击加载更多的按钮得到的是第二页的数据并不包含第一页的数据，需求是点击加载更多页面上展示的是前一页的数据和加载后的数据 数组与数组间的拼接用concat
            this.commentData = this.commentData.concat(res.data)
        },
        async getMore(){
        //    let result = await this.$http.get('/getMore');
        //    console.log(result);
            // this.commentData = result
            this. pageindex++
            this.getComment()
            // console.log(this.commentData);
        },
        async publishComment(){
            if(this.msg.trim().length==0) {
                return Toast('请填写评论内容')
            };
            //用axios跨域发送post请求时，请求参数默认是 'name=zhangsan&age=20'的形式若参数传递的是json数据类型则会报错这时要将 json数据转化成 name=zhangsan&age=20 的格式
            let { data } = await this.$http.post('/api/postcomment','content='+this.msg.trim());
            this.msg=''
            this.commentData.unshift({
                username:data.username,
                add_time:data.add_time,
                content:data.content
            });

            // console.log(result.data.content);
            // console.log(data);
        }
    },
    props:['newsid']

}
</script>

<style lang="less" scoped>
    textarea {
        margin: 0;
        font-size: 14px;
    }

    .box h4 {
        margin: 20px 0;
        text-align: center;
    }

    .cmt-list {
        .cmt-item {
            line-height: 30px;
            .cmt-item-title {
                margin-top: 5px;
                background: #ddd;
                font-size: 14px;
            }
            .cmt-item-body {
                font-size: 13px;
                text-indent: 2em;
            }
        }
    }
</style>